package com.said.today.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.said.today.dto.Result;
import com.said.today.entity.ShopType;
import com.said.today.mapper.ShopTypeMapper;
import com.said.today.service.IShopTypeService;
import com.said.today.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result shopType() {
        String key = RedisConstants.SHOP_TYPE;
        // 1.从redis中查询商户类型
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        // 2.判断商户类型是否存在
        if (StrUtil.isNotBlank(shopTypeJson)) {
            // 3.存在，直接返回
            // 反序列化
            List<ShopType> shopTypeList = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(shopTypeList);
        }
        // 4.不存在，查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        if (shopTypeList == null) {
            // 5.不存在，返回错误
            return Result.fail("商户类型不存在");
        }
        // 6.存在，写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopTypeList));
        // 返回
        return Result.ok(shopTypeList);
    }
}
